<template>
  <div>
    <div class="flex_js m_bottom15">
      <div class="tabs_box">
        <div :class="activeName == 1 ? 'select' : ''" @click="activeName = 1">
          <p>模块启用配置</p>
          <div></div>
        </div>
        <div :class="activeName == 2 ? 'select' : ''" @click="activeName = 2">
          <p>模板库选择</p>
          <div></div>
        </div>
        <div :class="activeName == 3 ? 'select' : ''" @click="activeName = 3">
          <p>算法选择</p>
          <div></div>
        </div>
        <div :class="activeName == 4 ? 'select' : ''" @click="activeName = 4">
          <p>设备选择</p>
          <div></div>
        </div>
      </div>
      <setTable
        :data="header_list"
        :height_size="height_size"
        @changeShowTable="
          (e) => {
            header_list[e].showTable = !header_list[e].showTable;
          }
        "
        @resetTableSet="
          () => {
            header_list.forEach((item) => {
              item.showTable = true;
            });
          }
        "
        @changeHeightSize="
          (e) => {
            height_size = e;
          }
        "
      ></setTable>
    </div>
    <el-table
      :data="list"
      max-height="800"
      row-key="id"
      border
      v-loading="loading"
      :default-sort="{ prop: 'sort', order: 'ascending' }"
      :row-style="{
        height: height_size == 2 ? '50px' : '',
      }"
      :cell-style="{
        padding: height_size == 3 ? '0' : '',
      }"
    >
      <el-table-column label="序号" type="index" width="80px"></el-table-column>
      <el-table-column
        label="模块名称"
        prop="name"
        v-if="activeName == 1"
      ></el-table-column>
      <el-table-column
        label="功能说明"
        prop="type"
        v-if="activeName == 1"
      ></el-table-column>
      <el-table-column
        label="模板库"
        prop="name"
        v-if="activeName == 2"
      ></el-table-column>
      <el-table-column label="算法" prop="name" v-if="activeName == 3"></el-table-column>
      <el-table-column
        label="设备厂家"
        prop="name"
        v-if="activeName == 4"
      ></el-table-column>
      <el-table-column
        label="设备型号"
        prop="name"
        v-if="activeName == 4"
      ></el-table-column>

      <el-table-column label="启/停用">
        <template #default="scope: any">
          <el-switch
            v-if="activeName == 2"
            active-color="#3580EB"
            inactive-color="#ABACAE"
            v-model="scope.row.isOpen"
            inline-prompt
            @change="update_mould(scope)"
          ></el-switch>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { days } from "@/utils/check_role"; // 权限校验
import setTable from "@/view/components/setTable.vue";
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { useStore } from "vuex";
import { getCookie } from "@/utils/cookie";
const store = useStore();
const height_size = ref();
const header_list = ref();
const activeName = ref(1);
const loading = ref(false);
watch(activeName, () => {
  console.log(activeName.value);
  list.value = [];
  if (activeName.value == 1) {
    get_price_item_list(); // 模块表
  } else if (activeName.value == 2) {
    // get_mould_list() //模板库
    // TODO
  } else if (activeName.value == 3) {
    // TODO
    list.value = [];
  }
});
const enterprise_id = computed(() => {
  return store.state.enterprise_id != "" // 当前登录企业 vuex > cookie > list[0]
    ? store.state.enterprise_id
    : getCookie("enterprise_id");
});
onMounted(() => {
  EventBus.on("refresh", () => {
    if (activeName.value == 1) {
      get_price_item_list(); // 模块表
    } else if (activeName.value == 2) {
      // get_mould_list() //模板库
      // TODO
    } else if (activeName.value == 3) {
      // TODO
      list.value = [];
    }
  });
});
onUnmounted(() => {
  EventBus.off("refresh");
  //   EventBus.off('complete')
  EventBus.off("pay_succ");
});
const list = ref([]);
const get_price_item_list = () => {
  axios
    .request({ url: serviceApi.price_item_list, method: "post" })
    .then((res) => {
      list.value = [];
      res.data.forEach((item) => {
        if (item.id == "5") {
          list.value.push(item);
        }
      });
      get_account_item_itemInfo();
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const update_mould = (e) => {
  console.log(e);
  let params = { isEnable: e.row.isOpen };
  axios
    .request({
      url: serviceApi.mould_list_updateIsEnable + "/" + e.row.id,
      method: "put",
      params,
    })
    .then((res) => {
      return;
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const get_account_item_itemInfo = () => {
  store.commit("set_organization_days", "");
  console.log(JSON.parse(getCookie("user_info")));
  axios
    .request({
      url: serviceApi.account_item_itemInfo,
      method: "post",
      data: {
        enterpriseId: enterprise_id.value,
        // memberId: JSON.parse(getCookie('user_info')).id,
      },
    })
    .then((res) => {
      console.log(res);
      list.value.forEach((item) => {
        res.data.some((item1) => {
          if (item1.itemId == item.id) {
            item.expireTime = item1.expireTime;
            item.is_term = true;
          }
          if (item1.itemId == 5 && item1.expireTime > Date.parse(new Date() as any)) {
            console.log(213);
            let dayss = days(item1.expireTime, Date.parse(new Date() as any)); // 剩余天数
            // save_enterprise_route()
            get_role_list();
            store.commit("set_organization_days", dayss);
          }
        });
      });
    })
    .catch((err) => {
      ElMessage.error(err);
    });
};
const get_role_list = () => {
  axios
    .request({ url: serviceApi.enterprise_role_list, method: "post" })
    .then((res) => {
      console.log(res.data);
      if (res.data === null) {
        ElMessage.warning("该企业尚未给你相关权限");
        return;
      }
      console.log(arrToTree(ArrSet(res.data, "id")));
      let list = arrToTree(ArrSet(res.data, "id"));
      //   if (store.state.current_enterprise_level < 4) {
      //     if (
      //       store.state.organization_days == '' ||
      //       store.state.organization_days < 1
      //     ) {
      //       // 没有购买组织  删除路由
      //       if (list[1] && list[1].name == '集团管理') {
      //         list.splice(1, 1)
      //       }
      //     }
      //   }
      store.commit("set_role_list", list);
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
// 数组对象 id 去重
const ArrSet = (Arr, id) => {
  var obj = {};
  const arrays = Arr.reduce((setArr, item) => {
    obj[item[id]] ? "" : (obj[item[id]] = true && setArr.push(item));
    return setArr;
  }, []);
  return arrays;
};
const arrToTree = (list) => {
  var map = {};
  var result = [];
  list.forEach((item) => {
    map[item.id] = item;
  });
  list.forEach((item) => {
    item.label = item.name;
    item.value = item.id;
    let parent = map[item.parentId];
    if (parent && item.type != 4) {
      if (!parent.children) {
        parent.children = [];
        parent.children.push(item);
      } else {
        var a = parent.children.some((e) => {
          return e.id == item.id;
        });
        if (!a) {
          parent.children.push(item);
        }
      }
      parent.children.sort((a, b) => {
        return a.sort - b.sort;
      });
    } else if (!parent && item.type != 4) {
      result.push(item);
      result.sort((a, b) => {
        return a.sort - b.sort;
      });
    }
  });
  return result;
};
</script>

<style lang="scss" scoped>
.tabs_box {
  display: flex;
  align-items: center;
  > div {
    cursor: pointer;
    p {
      padding: 0 20px;
      height: 25px;
    }
    > div {
      width: 28px;
      height: 3px;
      background-color: #fff;
      margin: 0 auto;
    }
  }
  .select {
    color: #3580eb;
    > div {
      background-color: #3580eb;
    }
  }
}
</style>
